import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

import 'package:flutter/foundation.dart';

typedef void OnPickImageCallback(
    double maxWidth, double maxHeight, int quality);

class ImagePickerPage extends StatefulWidget {
  ImagePickerPage({Key key}) : super(key: key);

  _ImagePickerPageState createState() => _ImagePickerPageState();
}

class _ImagePickerPageState extends State<ImagePickerPage> {
  //记录选择的照片
  File _image;
  final _picker = ImagePicker();

  //拍照
  Future _getImageFromCamera() async {
    var image =
        await _picker.getImage(source: ImageSource.camera, maxWidth: 400);
    final File file = File(image.path);
    setState(() {
      _image = file;
    });
  }

  //相册选择
  Future _getImageFromGallery() async {
    var image = await _picker.getImage(source: ImageSource.gallery);
    final File file = File(image.path);
    if (image != null) {
      print('image:不为空');
    } else {
      return;
    }
    setState(() {
      _image = file;
    });
  }

  ///老外写的
  Future<void> _pickImage(BuildContext context, ImageSource source) async {
    final _picker = ImagePicker();
    try {
      //确保我们可以获取权限
      // await Allper
      final tmpPickedFile = await _picker.getImage(source: source);
      print(source);
      if (tmpPickedFile != null) {
        File file = await File(tmpPickedFile.path);
        if (!await file.exists()) {
          throw Exception('请重试');
        }
        setState(() {
          _image = file;
        });
      }
    } catch (e) {
      print(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("选择图片并上传")),
      body: Container(
        child: ListView(
          children: <Widget>[
            RaisedButton(
              onPressed: () {
                // _getImageFromCamera();
                _pickImage(context, ImageSource.camera);
              },
              child: Text("照相机"),
            ),
            SizedBox(height: 10),
            RaisedButton(
              onPressed: () {
                _pickImage(context, ImageSource.gallery);
              },
              child: Text("相册"),
            ),
            SizedBox(height: 10),
            /**
             * 展示选择的图片
             */
            _image == null
                ? Text("no image selected")
                : Image.file(
                    _image,
                    fit: BoxFit.cover,
                  ),
          ],
        ),
      ),
    );
  }
}
